package com.letoy.study.utils;


import com.letoy.study.entity.AuthUser;
import com.letoy.study.entity.MyApi;
import com.letoy.study.service.ApiService;
import com.letoy.study.service.UserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Component
public class DynamicPermission {

    @Resource
    ApiService apiService;

    /**
     * 判断有访问API的权限
     *
     * @param request
     * @param authentication
     * @return
     */
    public boolean checkPermission(HttpServletRequest request,
                                   Authentication authentication) {

        Object principal = authentication.getPrincipal();
        String requestType = request.getRequestURI().split("/")[1];

        //判断是否能转换成UserDetails
        if (principal instanceof AuthUser) {

            AuthUser authUser = (AuthUser) principal;

            //获取当前登录的id
            String userId = authUser.getId();
            System.out.println("DynamicPermission userId = " + userId);


            AntPathMatcher antPathMatcher = new AntPathMatcher();
            //当前访问路径
            String requestURI = request.getRequestURI();
            //提交类型
            String urlMethod = request.getMethod();

            boolean AuthenticationResult = false;
            System.out.println("DynamicPermission requestURI = " + requestURI);
            if(requestType.equals("video")){

            }else {
                List<MyApi> myApiList = apiService.getMyApiListByUserId(userId);
                //匹配路由
                AuthenticationResult = myApiList.stream().anyMatch(item -> {
                    boolean hashAntPath = antPathMatcher.match(item.getUrl(), requestURI);
                    //判断请求方式是否和数据库中匹配（数据库存储：GET,POST,PƒUT,DELETE）
                    String dbMethod = item.getMethod();
                    //处理null，万一数据库存值
                    dbMethod = (dbMethod == null) ? "" : dbMethod;
                    int hasMethod = dbMethod.indexOf(urlMethod);
                    //两者都成立，返回真，否则返回假
                    return hashAntPath && (hasMethod != -1);
                });
            }


            System.out.println("是否在权限中：" + AuthenticationResult);
            return AuthenticationResult;

        } else {
            System.out.println("不是AuthUser类型！");
            return false;

        }

    }
}

























